package com.app.controller.statistics;

import com.alibaba.fastjson.JSONObject;
import com.app.common.Result;
import com.app.mapper.AttractInvestmentMapper;
import com.app.mapper.PlanBusinessMapper;
import com.app.mapper.PlanMapper;
import com.app.model.*;
import com.app.service.DepartmentService;
import com.app.service.KeyWorkService;
import com.app.service.ProjectProgressService;
import com.app.service.StriveForFundsService;
import com.app.util.DateUtil;
import com.app.vo.StatisticsVo;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 意见建议
 * -意见建议
 * ->点击进入：判断是否登录 获取手机号（可修改），标题，意见内容，是否匿名  /idea/save
 * <p>
 * 意见建议：
 * 提交 路径 /idea/save 请求方式 post 参数 title content openid
 * 查询 路径 /idea/get  请求方式 post 参数 userId
 */
@Controller
@RestController
@RequestMapping("/api")
@ResponseBody
public class StatisticsController {
    @Autowired
    private ProjectProgressService projectProgressService;


    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private PlanBusinessMapper planBusinessMapper;

    @Autowired
    private AttractInvestmentMapper attractInvestmentMapper;

    @Autowired
    private PlanMapper planMapper;
    @Autowired
    private KeyWorkService keyWorkService;
    @Autowired
    private StriveForFundsService striveForFundsService;


    /**
     * 根据类型查询重点投资项目
     *
     * @param type
     * @return
     */
    @GetMapping("/getProjectListByType")
    public Result<Object> getProjectListByType(Integer type) {
        return Result.success(projectProgressService.getProjectByStatus(type));
    }

    /**
     * 根据类型查询招商引资
     *
     * @param type
     * @return
     */
    @GetMapping("/getPlanBusinessByType")
    public Result<Object> getPlanBusinessByType(Integer type) {
        return Result.success(departmentService.getBusinessByStatus(type));
    }

    /**
     * 根据类型查询争取资金
     *
     * @param type
     * @return
     */
    @GetMapping("/getPlanByType")
    public Result<Object> getPlanByType(Integer type) {
        return Result.success(departmentService.getModelByStatus(type));
    }

    /**
     * 根据类型查询争取资金
     *
     * @return
     */
    @GetMapping("/getStatisticsCount")
    public Result<Object> getStatisticsCount() {
        StatisticsVo vo = new StatisticsVo();
        Calendar calendar = Calendar.getInstance();
        String year = String.valueOf(calendar.get(Calendar.YEAR));
        vo.setProjectCount(projectProgressService.getModelCount(0));
        vo.setProjectEndCount(projectProgressService.getModelCount(65));
        QueryWrapper<PlanBusinessModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("sum(task_plan) as sumAll");
        queryWrapper.eq("year", year);
        PlanBusinessModel ord = planBusinessMapper.selectOne(queryWrapper);
        vo.setBusinessCount(ord.getSumAll());
        QueryWrapper<BusinessModel> businessqueryWrapper = new QueryWrapper<>();
        businessqueryWrapper.select("sum(amount) as sumAll");
        businessqueryWrapper.eq("year", year);
        BusinessModel businessModel = attractInvestmentMapper.selectOne(businessqueryWrapper);
        vo.setBusinessEndCount(businessModel.getSumAll());
        QueryWrapper<PlanFundsModel> planFundsModelQueryWrapper = new QueryWrapper<>();
        planFundsModelQueryWrapper.select("sum(task_plan) as sumAll");
        planFundsModelQueryWrapper.eq("year", year);
        PlanFundsModel planFundsModel = planMapper.selectOne(planFundsModelQueryWrapper);
        vo.setTaskAllCount(planFundsModel.getSumAll());
        QueryWrapper<PlanFundsModel> planFundsModelQueryWrapperEnd = new QueryWrapper<>();
        planFundsModelQueryWrapperEnd.select("sum(task_plan) as sumAll").ne("status", 73);
        planFundsModelQueryWrapperEnd.eq("year", year);
        PlanFundsModel planFundsModel2 = planMapper.selectOne(planFundsModelQueryWrapperEnd);
        vo.setTaskEndAllCount(planFundsModel2.getSumAll());
        return Result.success(vo);
    }

    /**
     * 根据类型查询争取资金
     *
     * @return
     */
    @GetMapping("/getStatisticsSystem")
    public Result<Object> getStatisticsSystem() {
        List<SystemModel> systemModelList = departmentService.getSystemByPid(1);
        for (int i = 0; i < systemModelList.size(); i++) {
            int count = projectProgressService.getModelCountByStatusAndClass(63, systemModelList.get(i).getId());
            int count2 = projectProgressService.getModelCountByStatusAndClass(64, systemModelList.get(i).getId());
            int count3 = projectProgressService.getModelCountByStatusAndClass(65, systemModelList.get(i).getId());
            systemModelList.get(i).setBlueSum(count);
            systemModelList.get(i).setYellowSum(count2);
            systemModelList.get(i).setRedSum(count3);
        }
        return Result.success(systemModelList);
    }

    /**
     * 根据类型查询争取资金
     *
     * @return
     */
    @GetMapping("/getKeyWordList")
    public Result<Object> getKeyWordList() {

        List<DepartmentModel> departmentModelList = departmentService.getDepartmentModelAll();
        for (int i = 0; i < departmentModelList.size(); i++) {
            List<KeyWorkModel> keyWorkModels = keyWorkService.getListByDepartmentId(departmentModelList.get(i).getId());
            departmentModelList.get(i).setKeyWorkModelList(keyWorkModels);
        }
        for (int i = 0; i < departmentModelList.size(); i++) {
            if (departmentModelList.get(i).getKeyWorkModelList() == null || departmentModelList.get(i).getKeyWorkModelList().size() == 0) {
                departmentModelList.remove(i);
            }
        }
        return Result.success(departmentModelList);
    }

    /**
     * 根据类型查询争取资金
     *
     * @return
     */
    @GetMapping("/getFundMonthList")
    public Result<Object> getFundMonthList() throws ParseException {

        List<String> xData = new ArrayList<String>();
        List<Double> yData = new ArrayList<Double>();
        for (int i = 3, j = 0; i >= 0; i--) {
            Calendar calendar = Calendar.getInstance();
            int month = calendar.get(Calendar.MONTH) + 1;
            Date time = DateUtil.subMonth(new Date(), -i);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            String bir = sdf.format(time);
            Double count = striveForFundsService.getSumByMonth(bir);
            if (!yData.isEmpty()) {
                Double aDouble = yData.get(j);
                count = count + aDouble;
                j++;
            }
            xData.add(month - i + "月");
            yData.add(count);
        }

        List<String> xData2 = new ArrayList<String>();
        List<Double> yData2 = new ArrayList<Double>();
        for (int i = 3, j = 0; i >= 0; i--) {
            Calendar calendar = Calendar.getInstance();
            int month = calendar.get(Calendar.MONTH) + 1;
            Date time = DateUtil.subMonth(new Date(), -i);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            String bir = sdf.format(time);
            QueryWrapper<BusinessModel> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("sum(amount) as sumAll").like("finish_time", bir);
            BusinessModel ord = attractInvestmentMapper.selectOne(queryWrapper);
            Double count = 0.0;
            if (ord != null) {
                count = ord.getSumAll();
            }
            if (!yData2.isEmpty()) {
                Double aDouble = yData2.get(j);
                count = count + aDouble;
                j++;
            }
            xData2.add(month - i + "月");
            yData2.add(count);
        }
        JSONObject json = new JSONObject();
        JSONObject job = new JSONObject();
        job.put("xData", xData);
        job.put("yData", yData);
        json.put("striveForFunds", job);
        JSONObject job2 = new JSONObject();
        job2.put("xData", xData2);
        job2.put("yData", yData2);
        json.put("business", job2);
        return Result.success(json);
    }


    /**
     * 跟新数据脚本
     *
     * @return
     */
    @GetMapping("/updateProjectProgress")
    public Result<Object> updateProjectProgress() {

        List<ProjectModel> projectModelList = projectProgressService.getLIstByModel(null);
        List<StatusModel> statusModelList = projectProgressService.getStatusModelAll();

        for (int i = 0; i < projectModelList.size(); i++) {
            for (int j = 0; j < statusModelList.size(); j++) {
                if (projectModelList.get(i).getId() == statusModelList.get(j).getProjectId()) {
                    projectModelList.get(i).setRemarks(statusModelList.get(j).getRemarks());
                    projectProgressService.update(projectModelList.get(i));
                }
            }
        }

        return Result.success("操作成功");
    }

}
